package com.fowo.api.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.sys.entity.SysApplication;
import com.fowo.api.sys.mapper.SysApplicationMapper;
import com.fowo.api.sys.model.*;
import com.fowo.api.sys.service.SysRoleService;
import com.fowo.api.sys.service.SysApplicationService;
import com.fowo.api.user.model.CurrentUser;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class SysApplicationServiceImpl extends ServiceImpl<SysApplicationMapper, SysApplication> implements SysApplicationService {

    @Transactional
    @Override
    public SysApplication create(CreateSysApplication model) throws RException {
        if(getByAppName(model.getAppName()) != null) {
            throw new RException("此应用名称已经存在");
        }
        SysApplication sysApplication = new SysApplication();
        BeanUtils.copyProperties(model, sysApplication);
        sysApplication.doCreate();
        if(save(sysApplication)) {
            return sysApplication;
        }
        return null;
    }

    @Override
    public Page<SysApplicationItemVo> searchPage(SysApplicationSearch search) {
        search.initSort("sa.create_time desc", "sa.");
        Page<SysApplicationItemVo> page = getBaseMapper().searchPage(search.toPage(), search);
        return page;
    }

    @Override
    public List<SysApplicationItemVo> search(SysApplicationSearch search) {
        return getBaseMapper().search(search);
    }

    @Override
    public SysApplication getByAppName(String appName) {
        return getBaseMapper().selectOne(Wrappers.<SysApplication>query().eq("app_name", appName));
    }

    @Override
    public boolean removeById(Serializable id) {
        SysApplication SysApplication = getById(id);
        if(SysApplication != null && SysApplication.isProtected()) {
            throw new RException("被保护的数据不能删除");
        }
        return super.removeById(id);
    }
}
